<?php
/**
 * 公共函数库
 */
/**
 * 在scandir被禁用下，判断目录是否含有子文件
 * @param unknown_type $dir
 */
function dir_is_empty($dir){
	$handle = opendir($dir);
	$count = 0;
	if (!$handle){
			$this->_error = "open dir error";
			return false;
	}
	$flag = false;
	while (false !== ($filename = readdir($handle))){
		$count++;
	}
	closedir($handle);
	if ($count>2) {
		return true;
	}
	return false;
}
/**
 * 获取客户端Ip
 */
function getIP()
{
	if (getenv("HTTP_CLIENT_IP"))
		$ip = getenv("HTTP_CLIENT_IP");
	else if(getenv("HTTP_X_FORWARDED_FOR"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	else if(getenv("REMOTE_ADDR"))
		$ip = getenv("REMOTE_ADDR");
	else 
		$ip = "0.0.0.0";
		
	return $ip;
}
/**
* 字符串加密、解密函数
* @param	string	$txt		字符串
* @param	string	$operation	ENCODE为加密，DECODE为解密，可选参数，默认为ENCODE，
* @param	string	$key		密钥：数字、字母、下划线
* @param	string	$expiry		过期时间
* @return	string
*/
function sysencrypt($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
	$key_length = 4;
	$key = md5($key != '' ? $key : 'UxyLiI2z9bh2TgzhGOwp');
	$fixedkey = md5($key);
	$egiskeys = md5(substr($fixedkey, 16, 16));
	$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
	$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
	$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));

	$i = 0; $result = '';
	$string_length = strlen($string);
	for ($i = 0; $i < $string_length; $i++){
		$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
	}
	if($operation == 'ENCODE') {
		return $runtokey . str_replace('=', '', base64_encode($result));
	} else {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	}
}
/**
 * 编码转换
 * Enter description here ...
 * @param unknown_type $arr
 */
function array_iconvdecode($arr){
		$iconv = iconv('utf-8', 'gbk//TRANSLIT', var_export($arr,true).';');
		if(empty($iconv)){
			$iconv = ';';
		}
        return eval('return '.$iconv);   
}
/**
 * 导出csv文件
 * name 导出文件名
 * data 二维数组如array(
 * 	array(),
 * 	array()
 * )
 * @param unknown_type $name
 * @param unknown_type $data
 */
function exportcsv($name,$data){
	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition: attachment;filename="' . $name . '.csv"');
	header('Cache-Control: max-age=0');
	$limit = 1000;
	$i = 0;
	$fp = fopen('php://output', 'a');
	$decode = array_iconvdecode($data);
	foreach ($decode as $val){
		$val = array_values($val);
		$i++;
		if($i === $limit)
		{
			ob_flush();
			flush();
			$i = 0;
		}
		fputcsv($fp,$val);
	}
	fclose($fp);
}
/**
 * 过滤魔术引号选项
 * @version 2014-11-06
 */
function filter_default(&$value){
	if (get_magic_quotes_gpc()) {
		$value = stripslashes($value);
	}else{
		$value = $value;
	}
}

/**
 * curl get data
 */
function getdata($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    // 	curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
/**
 * 生成验证码
 */
function createcode(){
    $code=array('M','F','V','W','R','L','T','H','N','G','P','4','E','5','Q','C','J','7','D','U','X','8','B','3','6','9','K','Y','S','A');
    $length = count($code);
    $cache = cache(array('type'=>'File','expire'=>0,'temp'=>RUNTIME_PATH.'Temp/code/'));
    $cachenum = $cache->get('dis_authcode_num');
    $index1 = isset($cachenum['index1'])?$cachenum['index1']:0;
    $index2 = isset($cachenum['index2'])?$cachenum['index2']:0;
    $index3 = isset($cachenum['index3'])?$cachenum['index3']:0;
    $index4 = isset($cachenum['index4'])?$cachenum['index4']:0;
    $index5 = isset($cachenum['index5'])?$cachenum['index5']:0;
    $index6 = isset($cachenum['index6'])?$cachenum['index6']:0;
    $index6 += 1;
    if($index6>=$length){
        $index6 %= $length;
        $index5 += 1;
        if($index5>=$length){
            $index5 %= $length;
            $index4 += 1;
            if ($index4>=$length) {
                $index4 %= $length;
                $index3 += 1;
                if($index3>=$length){
                    $index %= $length;
                    $index2 +=1;
                    if($index2>=$length){
                        $index2 %= $length;
                        $index1 += 1;
                        if($index1>=$length){
                            $index1 %= $length;
                        }
                    }
                }
            }
        }
    }
    $list = array(
        'index1'=>$index1,
        'index2'=>$index2,
        'index3'=>$index3,
        'index4'=>$index4,
        'index5'=>$index5,
        'index6'=>$index6
    );
    $cache->set('dis_authcode_num',$list);
    return $code[$index1].$code[$index2].$code[$index3].$code[$index4].$code[$index5].$code[$index6];
     
}
